package log

import (
	"context"
	"github.com/natefinch/lumberjack"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"os"
	"proxy/conf"
)

func Init(mode string) (err error) {
	var logger = *conf.Conf.LogConfig
	writeSyncer := getLogWriter(
		logger.Filename,
		logger.MaxSize,
		logger.MaxBackups,
		logger.MaxAge,
	)
	encoder := getEncoder()
	var lv = new(zapcore.Level)
	err = lv.UnmarshalText([]byte(logger.Level))
	if err != nil {
		return err
	}
	var core zapcore.Core
	if mode == "dev" {
		consoleEncoder := zapcore.NewConsoleEncoder(zap.NewProductionEncoderConfig())
		core = zapcore.NewTee(
			zapcore.NewCore(encoder, writeSyncer, lv),
			zapcore.NewCore(consoleEncoder, zapcore.Lock(os.Stdout), zap.DebugLevel))
	} else {
		core = zapcore.NewCore(encoder, writeSyncer, lv)
	}
	lg := zap.New(core, zap.AddCaller(), zap.AddCallerSkip(1))
	zap.ReplaceGlobals(lg)
	return
}
func getEncoder() zapcore.Encoder {
	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.EncodeTime = zapcore.TimeEncoderOfLayout("2006-01-02 15:04:05.000")
	encoderConfig.TimeKey = "time"
	encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
	encoderConfig.EncodeDuration = zapcore.SecondsDurationEncoder
	encoderConfig.EncodeCaller = zapcore.ShortCallerEncoder
	return zapcore.NewJSONEncoder(encoderConfig)
}

func getLogWriter(fn string, maxSize, maxBackup, maxAge int) zapcore.WriteSyncer {
	lumberjackLogger := &lumberjack.Logger{
		Filename:   fn,
		MaxSize:    maxSize,
		MaxBackups: maxBackup,
		MaxAge:     maxAge,
	}
	return zapcore.AddSync(lumberjackLogger)
}

func Info(ctx context.Context, msg string, fields ...zapcore.Field) {
	zap.L().Info(msg, fields...)
}
func Debug(ctx context.Context, msg string, fields ...zapcore.Field) {
	zap.L().Debug(msg, fields...)
}
func Warn(ctx context.Context, msg string, fields ...zapcore.Field) {
	zap.L().Warn(msg, fields...)
}
func Error(ctx context.Context, msg string, fields ...zapcore.Field) {
	zap.L().Error(msg, fields...)
}
func Fatal(ctx context.Context, msg string, fields ...zapcore.Field) {
	zap.L().Fatal(msg, fields...)
}
